<template>
  <div class="modal-edit-box">
    <div class="drag-import-box" v-if="showUploadArea" @drop="dropHandler" @click="openFileDialog">
      <Icon type="ios-cloud-upload" />
      <div>{{$t('module.modelList.uploadPrompt')}}</div>
    </div>
    <input
      ref="fileElem"
      style="visibility: hidden;"
      type="file"
      :accept="acceptTypes"
      @change="selectedFile"
    />
    <div class="copy-prompt" v-if="showCopyPrompt">{{$t('module.modelList.copyPrompt')}}</div>
    <Form v-if="showForm" :model="modelForm" ref="modelTypeForm" :rules="rules" :label-width="120">
      <Row class="code-row-bg">
        <Col span="24" style="border:none;">
          <Form-item :label="$t('module.modelList.modelName')" prop="name">
            <Input
              :placeholder="$t('module.modelList.inputModelName')"
              v-model="modelForm.name"
              
            />
          </Form-item>
        </Col>
      </Row>
      <Row class="code-row-bg">
        <Col span="24" style="border:none;">
          <Form-item :label="$t('module.modelList.modelKey')" prop="key">
            <Input
              v-if="!modelInfo.version || modelInfo.optType == 'copy'"
              :placeholder="$t('module.modelList.inputModelKey')"
              v-model="modelForm.key"
              
            ></Input>
            <Input
              v-if="modelInfo.version && modelInfo.optType != 'copy'"
              disabled
              :placeholder="$t('module.modelList.inputModelKey')"
              v-model="modelForm.key"
              
            ></Input>
          </Form-item>
        </Col>
      </Row>
      <Row class="code-row-bg">
        <Col span="24" style="border:none;">
          <Form-item :label="$t('module.modelList.description')" prop="productId">
            <Input
              placeholder
              type="textarea"
              v-model="modelForm.description"
              :autosize="{minRows: 2,maxRows: 5}"
              
            />
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import { updateModel, createModel, copyModel, importModel } from '@api/flowable/modelList.js'
const events = ['drop', 'dragleave', 'dragenter', 'dragover']
function preventDefault(e) {
  e.preventDefault()
}

export default {
  name: 'ModelEdit',
  props: {
    modelInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    const validateKey = (rule, value, callback) => {
      value = value && value.trim && value.trim()
      if (!value) {
        callback(new Error(this.$t('module.modelList.inputModelKey')))
      } else if (!new RegExp('^[a-zA-z]([a-zA-z0-9]|_|-)*$').test(value)) {
        callback(new Error(this.$t('module.modelList.modelKeyInvalid')))
      }

      callback()
    }

    return {
      acceptTypes: 'text/xml,application/xml',
      showCopyPrompt: this.modelInfo.optType === 'copy' ? true : false,
      showForm: this.modelInfo.optType === 'import' ? false : true,
      showUploadArea: this.modelInfo.optType === 'import' ? true : false,
      modelForm: {
        name: this.modelInfo.name,
        key: this.modelInfo.key,
        description: this.modelInfo.description || '',
        id: this.modelInfo.id || ''
      },
      rules: {
        name: [{ required: true, message: this.$t('module.modelList.inputModelName'), trigger: 'blur' }],
        key: [{ required: true, validator: validateKey, trigger: 'blur' }]
      },
      actions: [
        {
          text: this.$t('common.save'),
          theme: 'primary',
          handle: () => {
            this.save()
          },
          loading: false
        },
        {
          text: this.$t('common.close'),
          handle: () => {
            this.$emit('Close')
          }
        }
      ]
    }
  },
  created: function() {
    let titleText,
      modelText = this.$t('module.modelList.model')

    if (this.modelInfo.id) {
      if (this.modelInfo.optType === 'copy') {
        titleText = this.$t('module.modelList.copy') + modelText
        this.actions[0].text = this.$t('module.modelList.copy')
      } else {
        titleText = this.$t('common.edit') + modelText
      }
    } else {
      if (this.modelInfo.optType === 'import') {
        titleText = this.$t('module.modelList.import') + modelText
        this.actions[0].text = this.$t('module.modelList.import')
        this.actions[0].disabled = true
      } else {
        titleText = this.$t('common.create') + modelText
      }
    }

    this.$emit('SetTitle', titleText)
    this.$emit('SetPageWidth', 500)
    this.$emit('SetPageActions', this.actions)

    events.forEach(event => {
      document.addEventListener(event, preventDefault)
    })
  },
  beforeDestroy() {
    events.forEach(event => {
      document.removeEventListener(event, preventDefault)
    })
  },
  methods: {
    parseFile(fileList) {
      //检测是否是拖拽文件到页面的操作
      if (fileList.length == 0) {
        return
      }

      const file = fileList[0]
      let fileType = file.type || file.name.split('.').pop()
      if (this.acceptTypes.indexOf(fileType.toLowerCase()) < 0) {
        this.$Message.error({
          content: this.$t('module.modelList.importFileTypeLimit'),
          duration: 3
        })

        return
      }

      this.importFile = file
      let reader = new FileReader()
      reader.readAsText(file, 'UTF-8')
      const vm = this
      reader.onload = function() {
        let xmldom = new DOMParser().parseFromString(this.result, 'text/xml')
        let modelNode = xmldom.documentElement.getElementsByTagName('process')[0]
        if (modelNode) {
          vm.showCopyPrompt = true
          vm.showForm = true
          vm.modelForm.key = modelNode.getAttribute('id')
          vm.modelForm.name = modelNode.getAttribute('name')
          let documentation = modelNode.getElementsByTagName('documentation')[0]
          vm.modelForm.description = documentation == undefined ? '' : documentation
          vm.$set(vm.actions, 0, Object.assign({}, vm.actions[0], {disabled: false}));
          vm.$emit('SetPageActions', vm.actions)
        } else {
          vm.$Message.error({
            content: vm.$t('文件内容格式错误,请检查后重新上传！'),
            duration: 3
          })
        }
      }
    },
    dropHandler(e) {
      this.parseFile(e.dataTransfer.files)
    },
    selectedFile(e) {
      this.parseFile(e.target.files)
    },
    openFileDialog() {
      this.$refs.fileElem.click()
    },
    _processServiceResponse(res, promputText) {
      this.actions[0].loading = false
      if (res) {
        this.$Message.success({
          content: promputText,
          duration: 3
        })

        //关闭当前窗口
        this.$emit('Close', this.modelForm)
      }
    },
    save() {
      // if (this.modelInfo.optType === 'import' && !this.showForm) {
      //   this.$Message.error({
      //       content: this.$t('common.formValidateFailed'),
      //       duration: 3
      //     })
      //   return false
      // }
      this.$refs['modelTypeForm'].validate(valid => {
        if (valid) {
          this.actions[0].loading = true
          let { procTypeId } = this.modelInfo,
            modelForm = this.modelForm,
            process = this._processServiceResponse.bind(this)

          if (modelForm.id) {
            if (this.modelInfo.optType === 'copy') {
              copyModel(procTypeId, modelForm)
                .then(res => process(res, this.$t('module.modelList.copySuccess')))
                .catch(err => (this.actions[0].loading = false))
            } else {
              updateModel(modelForm)
                .then(res => process(res, this.$t('common.updateSuccess')))
                .catch(err => (this.actions[0].loading = false))
            }
          } else {
            if (this.modelInfo.optType === 'import') {
              importModel(procTypeId, modelForm, this.importFile)
                .then(res => process(res, this.$t('module.modelList.copySuccess')))
                .catch(err => (this.actions[0].loading = false))
            } else {
              createModel(procTypeId, modelForm)
                .then(res => process(res, this.$t('common.createSuccess')))
                .catch(err => (this.actions[0].loading = false))
            }
          }
        } else {
          this.$Message.error({
            content: $t('common.formValidateFailed'),
            duration: 3
          })
        }
      })
    }
  }
  // watch: {},
  // directives: {}
}
</script>
<style lang="less">
.modal-edit-box {
  .copy-prompt {
    text-align: center;
    padding: 5px 0;
    background-color: #cbe6cb;
    font-size: 16px;
    margin-bottom: 10px;
  }
  .drag-import-box {
    text-align: center;
    border: 1px dashed #dcdee2;
    font-size: 16px;
    padding: 10px 0;
    border-radius: 5px;

    &:hover {
      border-color: rgb(51, 153, 255);
      cursor: pointer;
    }

    .ivu-icon {
      font-size: 50px;
      color: rgb(51, 153, 255);
    }
  }
}
</style>
